package com.wutongyu.mannyburger;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import static android.content.Context.MODE_PRIVATE;

public class LoginFragment extends Fragment {

    private static final String TAG = "LoginFragment";
    private static final String PREF_NAME = "user_prefs";
    private static final String KEY_LOGGED_IN_PHONE = "logged_in_phone";
    
    private EditText editTextPhone;
    private EditText editTextPassword;
    private Button buttonLogin;
    private TextView textViewRegister;
    private TextView textViewForgotPassword;
    private UserDatabaseHelper dbHelper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_login, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        editTextPhone = view.findViewById(R.id.edit_text_phone);
        editTextPassword = view.findViewById(R.id.edit_text_password);
        buttonLogin = view.findViewById(R.id.button_login);
        textViewRegister = view.findViewById(R.id.text_view_register);
        textViewForgotPassword = view.findViewById(R.id.text_view_forgot_password);

        dbHelper = new UserDatabaseHelper(requireContext());

        buttonLogin.setOnClickListener(v -> attemptLogin());

        textViewRegister.setOnClickListener(v -> navigateToRegister());
        
        textViewForgotPassword.setOnClickListener(v -> navigateToForgotPassword());
        
        // 检查是否已经登录
        checkIfAlreadyLoggedIn();
    }
    
    private void checkIfAlreadyLoggedIn() {
        SharedPreferences prefs = requireActivity().getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        String savedPhone = prefs.getString(KEY_LOGGED_IN_PHONE, null);
        
        if (savedPhone != null && !savedPhone.isEmpty()) {
            // 用户已经登录，直接跳转到个人信息页面
            Log.d(TAG, "发现已保存的登录状态，用户: " + savedPhone);
            navigateToUserProfile(savedPhone);
        }
    }

    private void attemptLogin() {
        String phone = editTextPhone.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        // 基本验证
        if (TextUtils.isEmpty(phone)) {
            editTextPhone.setError("手机号不能为空");
            editTextPhone.requestFocus();
            return;
        }
        // 可选：添加更严格的手机号格式验证

        if (TextUtils.isEmpty(password)) {
            editTextPassword.setError("密码不能为空");
            editTextPassword.requestFocus();
            return;
        }

        // 数据库验证
        boolean isValidUser = dbHelper.checkUser(phone, password);

        if (isValidUser) {
            Toast.makeText(getContext(), "登录成功！", Toast.LENGTH_SHORT).show();
            Log.i(TAG, "用户 " + phone + " 登录成功");
            
            // 保存登录状态
            saveLoginState(phone);
            
            // 登录成功后跳转到用户个人信息页面
            navigateToUserProfile(phone);
        } else {
            Toast.makeText(getContext(), "登录失败，手机号或密码错误", Toast.LENGTH_SHORT).show();
            Log.w(TAG, "用户 " + phone + " 登录失败");
        }
    }
    
    private void saveLoginState(String phone) {
        SharedPreferences prefs = requireActivity().getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_LOGGED_IN_PHONE, phone);
        editor.apply();
        Log.d(TAG, "已保存登录状态，用户: " + phone);
    }
    
    private void navigateToUserProfile(String phone) {
        if (!isAdded() || getActivity() == null || getActivity().isFinishing()) {
            Log.w(TAG, "Fragment未添加或Activity已销毁，取消导航");
            return;
        }
        
        // 使用工厂方法创建带参数的Fragment
        UserProfileFragment userProfileFragment = UserProfileFragment.newInstance(phone);
        
        // 跳转到用户个人信息页面
        FragmentManager fragmentManager = getParentFragmentManager();
        if (fragmentManager.isStateSaved()) {
            Log.w(TAG, "FragmentManager状态已保存，取消导航");
            return;
        }
        
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.nav_host_fragment_container, userProfileFragment);
        transaction.commitAllowingStateLoss();
    }

    private void navigateToRegister() {
        if (!isAdded() || getActivity() == null || getActivity().isFinishing()) {
            Log.w(TAG, "Fragment未添加或Activity已销毁，取消导航");
            return;
        }
        
        Log.d(TAG, "导航到注册 Fragment");
        FragmentManager fragmentManager = getParentFragmentManager(); // 使用 getParentFragmentManager
        if (fragmentManager.isStateSaved()) {
            Log.w(TAG, "FragmentManager状态已保存，取消导航");
            return;
        }
        
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.nav_host_fragment_container, new RegisterFragment()); // 替换容器中的 Fragment
        transaction.addToBackStack(null); // 允许用户按返回键回到登录界面
        transaction.commitAllowingStateLoss();
    }
    
    private void navigateToForgotPassword() {
        if (!isAdded() || getActivity() == null || getActivity().isFinishing()) {
            Log.w(TAG, "Fragment未添加或Activity已销毁，取消导航");
            return;
        }
        
        Log.d(TAG, "导航到忘记密码 Fragment");
        FragmentManager fragmentManager = getParentFragmentManager();
        if (fragmentManager.isStateSaved()) {
            Log.w(TAG, "FragmentManager状态已保存，取消导航");
            return;
        }
        
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.nav_host_fragment_container, new ForgotPasswordFragment());
        transaction.addToBackStack(null); // 允许用户按返回键回到登录界面
        transaction.commitAllowingStateLoss();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
} 